//
//  LiveViewController.m
//  TILLiveSDKShow
//
//  Created by wilderliao on 16/11/9.
//  Copyright © 2016年 Tencent. All rights reserved.
//

#import "LiveViewController.h"
#import "UserViewManager.h"
#import "LiveViewController+ImListener.h"
#import "LiveViewController+AVListener.h"
#import "LiveViewController+Audio.h"
#import "LiveCallView.h"
//水波
#import "FirstWaves.h"
#import "SecondWaves.h"
#import "TheerWaves.h"
//功能View
#import "CheekFountionView.h"
//提示是否匹配到View
#import "CheekShowInfoView.h"
//用户信息View
#import "ReportView.h"
//用户详细信息
#import "CheekUserDetailedView.h"
//拉黑
#import "AlertViewExtension.h"
#import "ZXYAlertView.h"
//赠送礼物
#import "HRGiftView.h"
#import "GiftTopUpView.h"
//内购
#import <StoreKit/StoreKit.h>
//美颜
#import "SetBeautyView.h"


#import <TILFilterSDK/TILFilter.h>
@interface LiveViewController ()<QAVLocalVideoDelegate, QAVRemoteVideoDelegate,ILiveRoomDisconnectListener,CheekFountionViewDelegate,CheekUserDetailedViewDelegate,ReportViewDelegate,alertviewExtensionDelegate,HRGiftViewDelegate,GiftTopUpViewDelegate,SKProductsRequestDelegate, SKPaymentTransactionObserver,ZXYAlertViewDelegate,CAAnimationDelegate>
/**
 功能
 */
@property (nonatomic, strong) CheekFountionView *fountionView;
/**
 渐变
 */
@property (nonatomic, strong) UIView              *gradually;//渐变背景
@property (nonatomic, strong) FirstWaves          *firstWare;
@property (nonatomic, strong) SecondWaves         *secondWare;
@property (nonatomic, strong) TheerWaves         *theerWare;
/**
 用户信息
 */
@property (nonatomic, strong) CheekVodeModel      *model;
/**
 匹配的用户信息
 */
@property (nonatomic, strong) ReportView          *reportView;
/**
 匹配的用户详细信息
 */
@property (nonatomic, strong) CheekUserDetailedView *detailedView;
/**
 是否匹配到用户提示
 */
@property (nonatomic, strong) CheekShowInfoView   *ShowInfo;
/**
 拉黑
 */
@property (nonatomic, strong) AlertViewExtension *alert;
/**
 举报类型
 */
@property (nonatomic, strong) NSArray *reportArr;
@property (nonatomic, strong) ZXYAlertView *alertX;

/**
 轮询定时器
 */
@property (nonatomic, strong) NSTimer       *pollingTimer;
@property (nonatomic, strong) NSString      *pollingFriend;
@property (nonatomic, strong) NSTimer       *beFriendTimer;
/**
 发送消息通知
 */
@property (nonatomic, strong) ILVLiveCustomMessage *CustomMessage;
/**
 赠送礼物
 */
@property (nonatomic, strong) HRGiftView *giftView;
@property (nonatomic, strong) UIView *giftBView;
@property (nonatomic, strong) NSArray *moneyArray;
@property (nonatomic, strong) NSArray *charmArray;
/**
 充值
 */
@property (nonatomic, strong) GiftTopUpView *topUpView;
/**
 支出钱
 */
@property (nonatomic, strong) NSString *moneyStr;
/**
 获得钻石
 */
@property (nonatomic, strong) NSString *payMoneyStr;
@property (nonatomic, strong) SKProductsRequest *requestSk;

/**
 苹果开发中心 商品ID
 */
@property (nonatomic, strong) NSString *productID;
@property (nonatomic, strong) UserpersionlInfoModel *infomodel;
/**
 视频时间
 */
@property (nonatomic, strong) NSTimer *VideoTimer;
@property (nonatomic, assign) CGFloat VideotimeFloat;
@property (nonatomic, assign) CGFloat VideotimeFloat2;
@property (nonatomic, assign) CGFloat VideoReducetime;
/**
 赠送或收到礼物时拼接的礼物名称
 */
@property (nonatomic, strong) NSString *NameGiftName;
/**
 赠送或收到礼物时拼接的礼物图片
 */
@property (nonatomic, strong) NSString *giftImageMini;
/**
 美颜
 */
@property (nonatomic, strong) TILFilter *tilFilter;
@property (nonatomic, assign) CGFloat  lastBeautyValue;
@property (nonatomic, assign) CGFloat  lastWhiteValue;


@end

@implementation LiveViewController


- (void)viewDidLoad{
    [super viewDidLoad];

    _reportArr = @[@"淫秽色情",@"政治反动",@"语言暴力",@"广告欺诈",@"虚假性别",@"其他内容",@"取消"];

    [self.navigationController setNavigationBarHidden:YES animated:YES];
    self.view.backgroundColor = Theme_Color_White;
    _pollingFriend =@"";
    _moneyArray = @[@"6",@"30",@"98",@"298"];
    _charmArray = @[@"42",@"210",@"686",@"2086"];
    
    [[ILiveRoomManager getInstance] setRemoteVideoDelegate:self];
    [[UserViewManager shareInstance] releaseManager];

    _NameGiftName = @"";
    
    //初始化直播
    [self initLive];
    //创建房间
    [self createRoom];
    //添加界面视图
    [self addSubviews];
}

- (void)initLive{
    TILLiveManager *manager = [TILLiveManager getInstance];
    [manager setAVListener:self];
    [manager setIMListener:self];
    [manager setAVRootView:self.view];
}

- (void)addSubviews{
    
    /***************************************/
    //渐变背景
    _gradually = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
    [self drawRect:_gradually.frame];

    //水波
    //第一个波浪
    _firstWare = [[FirstWaves alloc]initWithFrame:CGRectMake(0, _gradually.height-110, self.view.frame.size.width, 220)];
    _firstWare.alpha=0.6;
    //第二个波浪
    _secondWare = [[SecondWaves alloc]initWithFrame:CGRectMake(0, _gradually.height-110, self.view.frame.size.width, 220)];
    _secondWare.alpha=0.6;
    _theerWare = [[TheerWaves alloc]initWithFrame:CGRectMake(0, _gradually.height-110, self.view.frame.size.width, 220)];
    _theerWare.alpha=0.6;
    
    //展示是否已经匹配到用户
    _ShowInfo = [[CheekShowInfoView alloc] initWithFrame:CGRectMake(0, self.view.centerY-60*SCREEN_WIDTH_RATIO47, KScreenWidth, 160*SCREEN_WIDTH_RATIO47)];
    [_gradually addSubview:_firstWare];
    [_gradually addSubview:_secondWare];
    [_gradually addSubview:_theerWare];
    [_gradually addSubview:_ShowInfo];
    [self.view addSubview:_gradually];

    //是否有震荡效果
    [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(animateWave) userInfo:nil repeats:YES];
    /***************************************/
    
    /***************************************/
    self.reportView = [[ReportView alloc] initWithFrame:CGRectMake(15, 15, 200*SCREEN_WIDTH_RATIO47, 128*SCREEN_WIDTH_RATIO47)];
    self.reportView.delegate = self;
    self.reportView.hidden = YES;
    [self.view addSubview:self.reportView];
    [self.view bringSubviewToFront:self.reportView];
    /***************************************/
    
    /***************************************/
    _fountionView = [[CheekFountionView alloc] initWithFrame:CGRectMake(0, KScreenHeight-70*SCREEN_WIDTH_RATIO47, KScreenWidth, 50)];
    _fountionView.delegate = self;
    _fountionView.giftBtn.hidden = YES;
    [self.view addSubview:_fountionView];
    /***************************************/
    
    _VideotimeFloat = 60.0;
    _VideotimeFloat2 = 0.0;
    _VideoReducetime = 1.0;
    //    scheduledTimerWithTimeInterval方法初始化NSTimer, 不需要fire, 使用timerWithTimeInterval, 需要手写代码启动
}
#pragma  mark ============创建房间=============
- (void)createRoom{
    TILLiveRoomOption *option = [TILLiveRoomOption defaultHostLiveOption];
    option.avOption.autoHdAudio = YES;//使用高音质模式，可以传背景音乐
    option.roomDisconnectListener = self;
    option.imOption.imSupport = YES;
    [[ILiveRoomManager getInstance] setLocalVideoDelegate:self];
    [[TILLiveManager getInstance] createRoom:[[HQHttpManager getUserId] intValue] option:option succ:^{
        // 1. 创建房间成功   调用上报房间状态接口 。。。1 代表开始参加视频匹配
        [self requestSigType:@"1"];
        
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.view sendSubviewToBack:_gradually];

        });
        [self refreshBtn];

        NSLog(@"createRoom succ");
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        NSString *errinfo = [NSString stringWithFormat:@"module=%@,errid=%d,errmsg=%@",module,errId,errMsg];
        NSLog(@"createRoom fail.%@",errinfo);
        [SVProgressHUD setStatus:@"创建房间失败"];
        return ;
    }];
}
//连麦消息处理
- (void)onCustomMessage:(ILVLiveCustomMessage *)msg{
    WEAKSELF
    int cmd = msg.cmd;
    
    if (msg.type == ILVLIVE_IMTYPE_C2C)
    {
        switch (cmd)
        {
                /**
                 * 请求跨房连麦，C2C消息
                 */
            case ILVLIVE_IMCMD_LINKROOM_REQ:
            {
                [weakSelf recvLinkRoomReq:msg.sendId];
            }
                break;
                /**
                 * 同意跨房连麦，C2C消息   连接成功
                 */
            case ILVLIVE_IMCMD_LINKROOM_ACCEPT:
            {
                [weakSelf recvLinkRoomAccept:msg];
            }
                break;
            case AVIMCMD_Cancel_Back:{
                [weakSelf refreshBtnUser];
            }
                break;
                
            default:
                break;
        }
    }else if (msg.type == ILVLIVE_IMTYPE_GROUP){
      
    }
}
/**
 * 文本消息回调
 * @param  msg  文本消息类
 */
- (void)onTextMessage:(ILVLiveTextMessage *)msg{
    WEAKSELF
    
    if (msg.type == ILVLIVE_IMTYPE_C2C) {
        NSLog(@"收到消息了");
        [weakSelf receiveGift:msg.text];

    }

}
#pragma mark ================向服务端上传房间信息================
/**********连接  或  断开状态****/
- (void)requestSigType:(NSString *)type{
    
    [CheekVodeRequest getCheekVodeSigType:type success:^(id sucess) {
        if([sucess[@"code"] isEqualToString:@"ok"]){
            NSLog(@"上传状态信息完成%@",type);
        }
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark ================刷新 匹配用户请求==================
//当有一方断开时
- (void)refreshBtnUser{
    
    [self.view sendSubviewToBack:_gradually];
    [self.view bringSubviewToFront:self.reportView];
    _fountionView.giftBtn.hidden = YES;
    [_topUpView removeFromSuperview];
    [_giftBView removeFromSuperview];
    [_giftView removeFromSuperview];


    
    [self videoTimeStop];
    
    [[UserViewManager shareInstance].progressView removeFromSuperview];
    _VideotimeFloat = 60.0;
    _VideotimeFloat2 = 0.0;
    _VideoReducetime = 1.0;
    [[UserViewManager shareInstance] initializeAllData];
    
    
  
    _gradually.hidden = NO;
    self.reportView.hidden = YES;
    _ShowInfo.headerimg.image = [UIImage imageNamed:@"viedo_link_icon"];
    [_ShowInfo.nameImg  setTitle:@"正在寻找新朋友" forState:UIControlStateNormal];
    _ShowInfo.promptLab.text = @"有些人一旦错过就不在，喜欢赶紧加好友！";
 
    [[TILLiveManager getInstance] unLinkRoom:^{
        NSLog(@"结束跨房连麦了==========================");
     
        
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        
    }];
    [CheekVodeRequest getCheekVideoChatOver:[HQHttpManager getUserId] success:^(id sucess) {
        NSLog(@"断开连麦了============================");
        [self VideoChart];
    } failure:^(NSError *error) {
        
    }];
}
//刷新
- (void)refreshBtn{
    WEAKSELF
    [self.view sendSubviewToBack:_gradually];
    [self.view bringSubviewToFront:self.reportView];
    _fountionView.giftBtn.hidden = YES;
    [_topUpView removeFromSuperview];
    [_giftBView removeFromSuperview];
    [_giftView removeFromSuperview];
    [self.alert removeFromSuperview];
    [weakSelf videoTimeStop];

    [[UserViewManager shareInstance].progressView removeFromSuperview];
    _VideotimeFloat = 60.0;
    _VideotimeFloat2 = 0.0;
    _VideoReducetime = 1.0;
    
    if (_model.uid.length > 0) {
        
        [[UserViewManager shareInstance] initializeAllData];
        
        ILVLiveCustomMessage *overLimitMsg = [[ILVLiveCustomMessage alloc] init];
        overLimitMsg.cmd = (ILVLiveIMCmd)AVIMCMD_Cancel_Back;
        overLimitMsg.type = ILVLIVE_IMTYPE_C2C;
        overLimitMsg.recvId = _model.uid;
        [[TILLiveManager getInstance] sendOnlineCustomMessage:overLimitMsg succ:^{
            NSLog(@"发送在线自定义消息成功了");
            _gradually.hidden = NO;
            self.reportView.hidden = YES;
            _ShowInfo.headerimg.image = [UIImage imageNamed:@"viedo_link_icon"];
            [_ShowInfo.nameImg  setTitle:@"正在寻找新朋友" forState:UIControlStateNormal];
            _ShowInfo.promptLab.text = @"有些人一旦错过就不在，喜欢赶紧加好友！";
            
            [[TILLiveManager getInstance] unLinkRoom:^{
                NSLog(@"结束跨房连麦了==========================");
            } failed:^(NSString *module, int errId, NSString *errMsg) {
                
            }];
            
            [CheekVodeRequest getCheekVideoChatOver:[HQHttpManager getUserId] success:^(id sucess) {
                NSLog(@"断开连麦了============================");
                [weakSelf VideoChart];

            } failure:^(NSError *error) {
                
            }];

        } failed:^(NSString *module, int errId, NSString *errMsg) {
            NSLog(@"%@=================%@",module,errMsg);
        }];
    }else{
        [weakSelf VideoChart];
    }

 
}
- (void)VideoChart{
    WEAKSELF
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        NSString *lon =  [defaults objectForKey:@"longitude"];
        NSString *lat =  [defaults objectForKey:@"latitude"];
        
        [CheekVodeRequest getCheekVideoChatUid:[HQHttpManager getUserId] lon:lon lat:lat sex:_Sex success:^(id sucess) {
            if([sucess[@"code"] isEqualToString:@"ok"]){
                [weakSelf startLiveTimer];
                
                _model = [CheekVodeModel mj_objectWithKeyValues:sucess[@"res"]];
                //被连麦人ID
                [defaults removeObjectForKey:@"EventhewheatUid"];
                [defaults setValue:_model.uid forKey:@"EventhewheatUid"];
                [defaults synchronize];
                if (_model != nil) {
                    [_ShowInfo.headerimg sd_setImageWithURL:[NSURL URLWithString:HttpImgUrl(_model.photo)] placeholderImage:[UIImage imageNamed:@"llustration"]];
                    [_ShowInfo.nameImg  setTitle:_model.nickName forState:UIControlStateNormal];
                    
                    if ([_model.sex isEqualToString:@"1"]) {
                        [_ShowInfo.nameImg setImage:[UIImage imageNamed:@"viedo_sex_male_icon"] forState:UIControlStateNormal];
                    }else{
                        [_ShowInfo.nameImg setImage:[UIImage imageNamed:@"viedo_sex_fmale_icon"] forState:UIControlStateNormal];
                    }
                    _ShowInfo.promptLab.text = @"正在连接中....";
                    if (_model.uid.length > 0) {
                        //请求跨房连麦
                        NSString *ToUid = [NSString stringWithFormat:@"%@",_model.uid];
                        [weakSelf linkRoomRequest:ToUid];
                    }
                }
            }
        } failure:^(NSError *error) {
            
        }];
        
    });
}
/***********退出房间*************/
-(void)quitRommType:(UIButton *)sender{
    WEAKSELF
    //通知服务器  退出房间
    [weakSelf requestSigType:@"0"];
    //发送C2C消息
    ILVLiveCustomMessage *overLimitMsg = [[ILVLiveCustomMessage alloc] init];
    overLimitMsg.type = ILVLIVE_IMTYPE_C2C;
    overLimitMsg.cmd = (ILVLiveIMCmd)AVIMCMD_Cancel_Back;
    overLimitMsg.recvId = _model.uid;
    [weakSelf videoTimeStop];

    [[TILLiveManager getInstance] sendOnlineCustomMessage:overLimitMsg succ:^{
        
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        
    }];
    
    [[TILLiveManager getInstance] unLinkRoom:^{
        
     
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        
    }];
    
    //退出房间
    [[TILLiveManager getInstance] quitRoom:^{
        
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
        
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        
        NSLog(@"exit room fail.module=%@,errid=%d,errmsg=%@",module,errId,errMsg);
        
        [weakSelf dismissViewControllerAnimated:YES completion:nil];
        
    }];
}
#pragma mark ==========同意方调用用户信息===连麦==========
//发送连麦消息
- (void)linkRoomRequest:(NSString *)fromId{
    
    [[TILLiveManager getInstance] linkRoomRequest:fromId succ:^{
        NSLog(@"发送连麦成功");
        

    } failed:^(NSString *module, int errId, NSString *errMsg) {
        NSLog(@"失败");
    }];
}
//同意跨房连麦
- (void)recvLinkRoomReq:(NSString *)fromId{
    //同意跨房连麦
    WEAKSELF
    [[TILLiveManager getInstance] acceptLinkRoom:fromId succ:^{
        NSLog(@"accpet");
        
        //向业务后台请求直播间号
        
        NSString *lon =  [defaults objectForKey:@"longitude"];
        NSString *lat =  [defaults objectForKey:@"latitude"];
        
        [CheekVodeRequest getCheekVideoChatUid:[HQHttpManager getUserId] lon:lon lat:lat sex:@"2" success:^(id sucess) {
            _model = [CheekVodeModel mj_objectWithKeyValues:sucess[@"res"]];
            if (_model != nil) {
                [_ShowInfo.headerimg sd_setImageWithURL:[NSURL URLWithString:HttpImgUrl(_model.photo)] placeholderImage:[UIImage imageNamed:@"llustration"]];
                [_ShowInfo.nameImg  setTitle:_model.nickName forState:UIControlStateNormal];
                
                if ([_model.sex isEqualToString:@"1"]) {
                    [_ShowInfo.nameImg setImage:[UIImage imageNamed:@"viedo_sex_male_icon"] forState:UIControlStateNormal];
                }else{
                    [_ShowInfo.nameImg setImage:[UIImage imageNamed:@"viedo_sex_fmale_icon"] forState:UIControlStateNormal];
                }
                _ShowInfo.promptLab.text = @"正在连接中....";
            }
            weakSelf.reportView.model = _model;
            [defaults removeObjectForKey:@"EventhewheatUid"];
            [defaults setValue:_model.uid forKey:@"EventhewheatUid"];
            [defaults synchronize];

            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                _gradually.hidden = YES;
                weakSelf.reportView.hidden = NO;
                _fountionView.giftBtn.hidden = NO;
                
                [[UserViewManager shareInstance].progressView removeFromSuperview];
                _VideotimeFloat = 60.0;
                _VideotimeFloat2 = 0.0;
                _VideoReducetime = 1.0;
                [[UserViewManager shareInstance]progressViewInitDate];
                
                //开启定时器
                [weakSelf videoTimeStop];
                    _VideoTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(Videotimer:) userInfo:nil repeats:YES];

                if (![_Sex isEqualToString:@"2"]) {
                    [CheekVodeRequest getCheekScreeningPayCharm:[HQHttpManager getUserId] charm:@"2" success:^(id sucess) {
                        [weakSelf getUserInfoRequestDate];
                    } failure:^(NSError *error) {
                        
                    }];
                    
                }
         
            });
            
            
        } failure:^(NSError *error) {
            
        }];
        
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        NSLog(@"accpet");
    }];
    
    
}
//连接成功
- (void)recvLinkRoomAccept:(ILVLiveCustomMessage *)msg{

    
    WEAKSELF
    NSString *LinkSig = _model.linkSig;
    
    NSString *sendId = [NSString stringWithFormat:@"%@",msg.sendId];
    
    NSLog(@"%@------%@-------%@",_model.uid,sendId,LinkSig);
    
    [[TILLiveManager getInstance] linkRoom:[_model.uid intValue] identifier:sendId authBuff:LinkSig succ:^{
        NSLog(@"连接成功");

        weakSelf.reportView.model = _model;
        weakSelf.reportView.hidden = NO;
        _gradually.hidden = YES;
  
        _fountionView.giftBtn.hidden = NO;
        [[UserViewManager shareInstance].progressView removeFromSuperview];
        _VideotimeFloat = 60.0;
        _VideotimeFloat2 = 0.0;
        _VideoReducetime = 1.0;
        [[UserViewManager shareInstance]progressViewInitDate];
        [weakSelf videoTimeStop];
        _VideoTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:weakSelf selector:@selector(Videotimer:) userInfo:nil repeats:YES];
        
        
        if (![_Sex isEqualToString:@"2"]) {
            [CheekVodeRequest getCheekScreeningPayCharm:[HQHttpManager getUserId] charm:@"2" success:^(id sucess) {
                [weakSelf getUserInfoRequestDate];
            } failure:^(NSError *error) {
                
            }];
            
        }
        
        
    } failed:^(NSString *module, int errId, NSString *errMsg) {
        
        
        
}];
  
}
//视频时间计时方法
- (void)Videotimer:(NSTimer *)timer{
    WEAKSELF
    CGFloat senderFloatValue =     1.0/_VideotimeFloat*_VideoReducetime;
    _VideoReducetime++;
    _VideotimeFloat2 = _VideotimeFloat-_VideoReducetime;
    NSLog(@"_VideotimeFloat=======%f\n_VideotimeFloat2==========%f\n_VideoReducetime===========%f",_VideotimeFloat,_VideotimeFloat2,_VideoReducetime);
    
    NSLog(@"NSDate dateNSDate dateNSDate date%@",[NSDate date]);
    
    if (_VideotimeFloat2 == 0.0) {
        [weakSelf videoTimeStop];
        _VideotimeFloat = 60.0;
        _VideotimeFloat2 = 0.0;
        _VideoReducetime = 1.0;
        [[UserViewManager shareInstance].progressView removeFromSuperview];
    [weakSelf refreshBtn];

    }
    
   [UserViewManager shareInstance].progressView.progress = senderFloatValue;
    [UserViewManager shareInstance].progressView.timeFloat = _VideotimeFloat2;
}
- (void)videoTimeStop{
    if(_VideoTimer)
    {
        [_VideoTimer invalidate];
        _VideoTimer = nil;
    }
}
#pragma mark =================ReportViewDelegate===============
//举报
-(void)reportBtnClickAction:(UIButton *)sender{
    
    _alertX = [ZXYAlertView alertViewDefault];
    
    _alertX.delegate = self;
    
    _alertX.title = @"选择举报类型";
    
    _alertX.buttonArray = _reportArr;
    
    [self.view addSubview:self.alertX];
    
    [_alertX show];

    
}
//举报回调
- (void)alertView:(ZXYAlertView *)alertView clickedCustomButtonAtIndex:(NSInteger)buttonIndex {
    
    NSLog(@"---%ld",(long)buttonIndex);
    
    if (buttonIndex == 6) {
        
    }else{
        NSString *str = _reportArr[buttonIndex];
        
        
        [HcardHttpmanager getReportUid:[HQHttpManager getUserId] reportUid:_model.uid Img:@"" reason:str success:^(id result) {
            if ([result[@"code"] isEqualToString:@"ok"]) {
                [SVProgressHUD showWithStatus:@"举报成功"];
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
            }
        } failure:^(NSError *error) {
            
        }];
    }
    
}
//个人信息
-(void)headerBtnClick:(UIButton*)sender{
    self.detailedView = [[CheekUserDetailedView alloc] initWithFrame:CGRectMake(25*SCREEN_WIDTH_RATIO47, self.view.centerY-310*SCREEN_WIDTH_RATIO47/2, KScreenWidth-50*SCREEN_WIDTH_RATIO47, 310*SCREEN_WIDTH_RATIO47)];
    self.detailedView.delegate = self;
    self.detailedView.model = _model;
    self.detailedView.backgroundColor = [UIColor whiteColor];
    [self animationWithView:self.detailedView duration:0.3];
    
    [UIView animateWithDuration:0.25 animations:^{
        [self.view addSubview:self.detailedView];
        [self.view bringSubviewToFront:self.detailedView];

    }];
    
}
- (void)animationWithView:(UIView *)view duration:(CFTimeInterval)duration{
    
    CAKeyframeAnimation * animation;
    animation = [CAKeyframeAnimation animationWithKeyPath:@"transform"];
    animation.duration = duration;
    animation.removedOnCompletion = NO;
    
    animation.fillMode = kCAFillModeForwards;
    
    NSMutableArray *values = [NSMutableArray array];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.1, 0.1, 1.0)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.2, 1.2, 1.0)]];
    //    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(0.9, 0.9, 0.9)]];
    [values addObject:[NSValue valueWithCATransform3D:CATransform3DMakeScale(1.0, 1.0, 1.0)]];
    
    animation.values = values;
    animation.timingFunction = [CAMediaTimingFunction functionWithName: @"easeInEaseOut"];
    
    [view.layer addAnimation:animation forKey:nil];
}
//加好友
-(void)AddbuddyBtnAction:(UIButton *)sender{
    
    [CheekVodeRequest getCheekFriendHelloUid:[HQHttpManager getUserId] Wid:_model.uid success:^(id sucess) {
        
        if ([sucess[@"code"] isEqualToString:@"ok"]) {
            [SVProgressHUD showProgress:1 status:@"请求成功"];
         
            [self.reportView.AddbuddyBtn setTitle:@"已请求" forState:UIControlStateNormal];
            [self startbeFriendTimer];
        }else{
            [SVProgressHUD showProgress:1 status:@"请求失败"];
            
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    } failure:^(NSError *error) {
        
    }];
}
//发送好友请求后轮询
-(void)startbeFriendTimer{
    
    [self stopbeFriendTimer];
    _beFriendTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(beFriendTimer:) userInfo:nil repeats:YES];
    
}
//停止轮询
- (void)stopbeFriendTimer{
    if(_beFriendTimer)
    {
        [_beFriendTimer invalidate];
        _beFriendTimer = nil;
    }
}
//请求是否有添加好友请求
- (void)beFriendTimer:(NSTimer *)timer{
    [CheekVodeRequest getCheekBeFriendUid:[HQHttpManager getUserId] Wid:_model.uid success:^(id sucess) {
        if ([sucess[@"code"] isEqualToString:@"ok"]) {
            [self.reportView.AddbuddyBtn setTitle:@"已是好友" forState:UIControlStateNormal];
        }
    } failure:^(NSError *error) {
        
    }];
}
#pragma mark =====================CheekUserDetailedView=================
/**  关闭  */
-(void)ShutdownBtnClick:(UIButton *)sender{
    [self.detailedView removeFromSuperview];
}
/** 拉黑  */
-(void)shieldingBtnClick:(UIButton *)sender{
    self.alert =[[AlertViewExtension alloc]initWithFrame:CGRectMake(0, 0,KScreenWidth, KScreenHeight)];
    self.alert.delegate=self;
    [self.alert setbackviewframeWidth:KScreenWidth-80 Andheight:110];
    [self.alert settipeTitleStr:@"真的要将对方拉黑吗" Andfont:14];
    [self.view addSubview:self.alert];
    [self.view bringSubviewToFront:self.alert];

}
//拉黑回调    是否有好友请求
-(void)clickBtnSelector:(UIButton *)btn{
    
    if ([_pollingFriend isEqualToString:@"1"]) {
        if (btn.tag == 0) {
            [self.alert removeFromSuperview];
            [self.detailedView removeFromSuperview];
            
            NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
            [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
            NSNumber *numTemp = [numberFormatter numberFromString:_model.uid];
            [HQHttpManager pickWooWithUid:[HQHttpManager getUserId] wid:numTemp type:@(2) successBlock:^(BOOL isSuccess, NSDictionary *resultDic) {
                if (isSuccess) {
                    [SVProgressHUD showProgress:1 status:@"添加好友成功"];
                    [self.reportView.AddbuddyBtn setTitle:@"已添加" forState:UIControlStateNormal];
                }
            }];
         
        }else{
            [self.alert removeFromSuperview];
            [self.detailedView removeFromSuperview];
            
        }
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [SVProgressHUD dismiss];
        });
    }else{
        if (btn.tag == 0) {
            [self.alert removeFromSuperview];
            [self.detailedView removeFromSuperview];
            [HcardHttpmanager blackFriendWithWid:_model.uid Success:^(id result) {
                
                if ([result[@"code"] isEqualToString:@"ok"]) {
                    [self refreshBtn];
                }
                
            } failure:^(NSError *error) {
                
            }];
            
            
        }else{
            [self.alert removeFromSuperview];
            [self.detailedView removeFromSuperview];
            
        }

    }
}
#pragma mark ===============请求是否有好友消息轮询==============
-(void)startLiveTimer{

    [self stopLiveTimer];
    _pollingTimer = [NSTimer scheduledTimerWithTimeInterval:3 target:self selector:@selector(onPostHeartBeat:) userInfo:nil repeats:YES];

}
//请求是否有添加好友请求
- (void)onPostHeartBeat:(NSTimer *)timer{
  
    [CheekVodeRequest getCheekFriendRequestUid:[HQHttpManager getUserId] Wid:_model.uid success:^(id sucess) {
        
        if ([sucess[@"code"] isEqualToString:@"ok"]) {
            [self stopLiveTimer];
            [self timerPollingAlert];
            [self startbeFriendTimer];
        }
        
    } failure:^(NSError *error) {
        
    }];
    
}
- (void)timerPollingAlert{
    _pollingFriend = @"1";
    self.alert =[[AlertViewExtension alloc]initWithFrame:CGRectMake(0, 0,KScreenWidth, KScreenHeight)];
    self.alert.delegate=self;
    [self.alert setbackviewframeWidth:KScreenWidth-50 Andheight:110];
    [self.alert settipeTitleStr:@"对方请求添加您为好友" Andfont:14];
    [self.view addSubview:self.alert];
    [self.view bringSubviewToFront:self.alert];
}
//停止轮询
- (void)stopLiveTimer{
    if(_pollingTimer)
    {
        [_pollingTimer invalidate];
        _pollingTimer = nil;
    }
}
#pragma mark ===================赠送礼物===================
/*******************实例化礼物栏*******************/

-(void)CreateGiftBtnClick{
    
        _giftBView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
    
        _giftView = [[HRGiftView alloc] initWithFrame:CGRectMake(0, _giftBView.height-230, KScreenWidth, 230)];
    
        _giftView.delegate = self;
    
        _giftView.timeType = @"0";
        
        
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        [button addTarget:self action:@selector(buttongiftBViewRemove) forControlEvents:UIControlEventTouchUpInside];
        button.frame = CGRectMake(0, 0, KScreenWidth, KScreenHeight-_giftView.height);
        [_giftBView addSubview:button];
        
        
        CATransition *animation = [CATransition  animation];
        animation.duration = 0.2f;
        animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        animation.type = kCATransitionPush;
        animation.subtype = kCATransitionFromTop;
        [_giftBView.layer addAnimation:animation forKey:@"animation1"];
        [_giftBView  addSubview:_giftView];
        [self.view addSubview:_giftBView];

    _giftView.isShow = NO;
}

/*******************退出礼物栏*******************/

- (void)buttongiftBViewRemove{
    
    _giftView.hidden = YES;
    _giftBView.hidden= YES;
    _giftView.isShow =NO;
    CATransition *animation = [CATransition  animation];
    
    animation.duration = 0.2f;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromBottom;
    [self.giftBView.layer addAnimation:animation forKey:@"animtion2"];
    [UIView animateWithDuration:0.2 animations:^{
        
    }completion:^(BOOL finished) {
        [_giftBView removeFromSuperview];

        [_giftView removeFromSuperview];
    }];
    
}
/************接收礼物展示**********/
- (void)receiveGift:(NSString *)text{

    UIView *imageV = [[UIView alloc]initWithFrame:CGRectMake(0, KScreenHeight-360*SCREEN_WIDTH_RATIO47, KScreenWidth, 310*SCREEN_WIDTH_RATIO47)];
    
    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,imageV.width,imageV.height)];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    NSArray *dataArr = [[NSArray alloc] init];
    
    if (text.length) {
        dataArr = [[NSArray alloc] init];
        dataArr = [text componentsSeparatedByString:@","];
    }
    
    
    [imageView sd_setImageWithURL:[NSURL URLWithString:dataArr[1]] placeholderImage:[UIImage imageNamed:@"llustration"]];
    _VideotimeFloat = _VideotimeFloat+[dataArr[0] floatValue];
    _VideotimeFloat2 = _VideotimeFloat2+[dataArr[0] floatValue];
    _NameGiftName = dataArr[2];
    
    [imageV addSubview:imageView];

    
    UIImageView *nameGiftView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.centerY, KScreenWidth/2, 50)];
    
    nameGiftView.image = [UIImage imageNamed:@"gift_hint_button"];

    
    
    UILabel *GiftName = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, KScreenWidth/2-50-15, 40)];
    GiftName.textAlignment = NSTextAlignmentLeft;
    GiftName.text = [NSString stringWithFormat:@"收到%@",_NameGiftName];
    GiftName.font = FontP(17);
    GiftName.textColor = [UIColor whiteColor];
    
    [nameGiftView addSubview:GiftName];
    
    
    UIImageView *imageMinView = [UIImageView new];
    imageMinView.frame = CGRectMake(GiftName.right+1, 5, 40, 40);
    [imageMinView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@.2",dataArr[1]]]];
    [nameGiftView addSubview:imageMinView];
    
    
    CATransition * animation = [CATransition animation];
    animation.duration = 0.5;    //  时间
    animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromLeft;
    [nameGiftView.layer addAnimation:animation forKey:nil];
    [UIView animateWithDuration:1 animations:^{
        [self.view addSubview:nameGiftView];
        [self.view bringSubviewToFront:nameGiftView];
    }];

 
    
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [nameGiftView removeFromSuperview];

        CABasicAnimation *animation = nil;
        //缩放
        animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
        [animation setFromValue:@0.1];//设置起始值
        [animation setToValue:@1.];//设置目标值
        [animation setDelegate:self];//代理回调
        [animation setDuration:0.3];//设置动画时间，单次动画时间
        [animation setRemovedOnCompletion:NO];
        
        //you view need to replace
        [imageV.layer addAnimation:animation forKey:nil];
        
        
        [UIView animateWithDuration:1.5 animations:^{
            [self.view addSubview:imageV];
            [self.view bringSubviewToFront:imageV];
        }];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [imageV removeFromSuperview];
        });
    
    });

    
 
    

}

/*******************选中礼物赠送*******************/
- (void)didClickSendButton:(CheekGiftModel *)gift {
    NSLog(@"gift=%@",gift);
    WEAKSELF
    CheekGiftModel *giftmodel = gift;
    
    [HcardHttpmanager getuserInfocharmsuccess:^(id sucess) {
    
        UserInfocharmModel *model = sucess;
        NSInteger modelCharm = [model.charm intValue];
        NSInteger giftCharm = [giftmodel.charm intValue];
        if (modelCharm >= giftCharm) {
            NSLog(@"_model.uid%@=========%@giftmodel.giftId",_model.uid,giftmodel.giftId);
 
            [HcardHttpmanager giveGiftWithWid:_model.uid WithGiftId:giftmodel.giftId WithStatus:@"2" WithAskId:nil Success:^(id result) {
                if ([result[@"code"] isEqualToString:@"ok"]) {
                    _giftView.isShow = YES;

                    //发送C2C消息
                    ILVLiveTextMessage *overLimitMsg = [[ILVLiveTextMessage alloc] init];
                    overLimitMsg.type = ILVLIVE_IMTYPE_C2C;
                    overLimitMsg.recvId = _model.uid;
                    NSString *NameGiftName = giftmodel.name;
                    
                    NSString *str = [NSString stringWithFormat:@"%@,%@,%@", giftmodel.time,HttpImgUrl(giftmodel.img),NameGiftName];
                    
                    overLimitMsg.text = str;
                    
                    _VideotimeFloat = _VideotimeFloat+[giftmodel.time floatValue];
                    _VideotimeFloat2 = _VideotimeFloat2+[giftmodel.time floatValue];
                    
                    
                    
                    //礼物北京
                    UIView *imageV = [[UIView alloc]initWithFrame:CGRectMake(0, KScreenHeight-360*SCREEN_WIDTH_RATIO47, KScreenWidth, 310*SCREEN_WIDTH_RATIO47)];
                    //礼物
                    UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0,0,imageV.width,imageV.height)];
                    imageView.contentMode = UIViewContentModeScaleAspectFit;
          
                    [imageView sd_setImageWithURL:[NSURL URLWithString:HttpImgUrl(giftmodel.img)] placeholderImage:[UIImage imageNamed:@"llustration"]];
                    [imageV addSubview:imageView];
                    
                    
                    //小的礼物图背景
                    UIImageView *nameGiftView = [[UIImageView alloc] initWithFrame:CGRectMake(0, self.view.centerY, KScreenWidth/2, 50)];
                    nameGiftView.image = [UIImage imageNamed:@"gift_hint_button"];
                    //送出还是收到
                    UILabel *GiftName = [[UILabel alloc] initWithFrame:CGRectMake(15, 5, KScreenWidth/2-50-15, 40)];
                    GiftName.textAlignment = NSTextAlignmentLeft;
                    GiftName.text = [NSString stringWithFormat:@"送出%@",_NameGiftName];
                    GiftName.font = FontP(17);
                    GiftName.textColor = [UIColor whiteColor];
                    [nameGiftView addSubview:GiftName];
                    
                    //小的礼物图
                    UIImageView *imageMinView = [UIImageView new];
                    imageMinView.frame = CGRectMake(GiftName.right+1, 5, 40, 40);
                    [imageMinView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@.2",HttpImgUrl(giftmodel.img)]]];
                    [nameGiftView addSubview:imageMinView];
                    
                    
                    CATransition * animation = [CATransition animation];
                    animation.duration = 0.5;    //  时间
                    animation.type = kCATransitionPush;
                    animation.subtype = kCATransitionFromLeft;
                    [nameGiftView.layer addAnimation:animation forKey:nil];
                    [UIView animateWithDuration:1 animations:^{
                        [self.view addSubview:nameGiftView];
                        [self.view bringSubviewToFront:nameGiftView];
                    }];
                    
                    
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                        [nameGiftView removeFromSuperview];
                        
                        CABasicAnimation *animation = nil;
                        //缩放
                        animation = [CABasicAnimation animationWithKeyPath:@"transform.scale"];
                        [animation setFromValue:@0.1];//设置起始值
                        [animation setToValue:@1.];//设置目标值
                        [animation setDelegate:self];//代理回调
                        [animation setDuration:0.3];//设置动画时间，单次动画时间
                        [animation setRemovedOnCompletion:NO];
                        
                        //you view need to replace
                        [imageV.layer addAnimation:animation forKey:nil];

                        
                        [UIView animateWithDuration:1.5 animations:^{
                            [self.view addSubview:imageV];
                            [self.view bringSubviewToFront:imageV];
                        }];
                        
                        
                        
                        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                            imageV.hidden = YES;
                            [imageV removeFromSuperview];
                            
                        });

                        
                    });
  
                    
                    
                    [[TILLiveManager getInstance] sendTextMessage:overLimitMsg succ:^{
                        NSLog(@"send msg succ");
//                        [SVProgressHUD showSuccessWithStatus:@"礼物赠送成功"];
                        [weakSelf buttongiftBViewRemove];
                    } failed:^(NSString *module, int errId, NSString *errMsg) {
                        NSLog(@"createRoom fail.module=%@,errid=%d,errmsg=%@",module,errId,errMsg);
                    }];

                    
                }else{
                    [weakSelf CheektopUpButton];
                }
            } failure:^(NSError *error) {
                
            }];
        }else{
            [weakSelf CheektopUpButton];
        }
        
    } failure:^(NSError *error) {
        
    }];
}
/**********充值*************/
- (void)didClickRechargeButton {
    [self CheektopUpButton];
}

/*********************实例化充值栏********************/
-(void)CheektopUpButton{
    WEAKSELF
    //关闭礼物栏
    [weakSelf buttongiftBViewRemove];
    
    _topUpView = [[GiftTopUpView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, KScreenHeight)];
    _topUpView.charmArray = _charmArray;
    _topUpView.moneyArray = _moneyArray;
    _topUpView.delegate = self;
    CATransition *animation = [CATransition  animation];
    animation.duration = 0.2f;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromTop;
    [_topUpView.layer addAnimation:animation forKey:@"animation1"];
    [self.view addSubview:_topUpView];
}

/**
 返回礼物
 */
-(void)backGiftButtonClick{
    CATransition *animation = [CATransition  animation];
    animation.duration = 0.2f;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromBottom;
    [self.topUpView.layer addAnimation:animation forKey:@"animtion2"];
    [UIView animateWithDuration:0.2 animations:^{
        
    }completion:^(BOOL finished) {
        [_topUpView removeFromSuperview];
        [self CreateGiftBtnClick];
    }];
}
#pragma mark ===================美颜===============
- (void)BeautyButtonClick{
    WEAKSELF
    self.tilFilter = [[TILFilter alloc] init];
    [[ILiveRoomManager getInstance] setLocalVideoDelegate:self];

    SetBeautyView *beautyView = [[SetBeautyView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth,KScreenHeight)];
    
    CATransition *animation = [CATransition  animation];
    animation.duration = 0.2f;
    animation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    animation.type = kCATransitionPush;
    animation.subtype = kCATransitionFromTop;
    [beautyView.layer addAnimation:animation forKey:@"animation1"];
    [self.view  addSubview:beautyView];

    beautyView.changeCompletion = ^(BeautyViewType type, CGFloat beauty) {
        if (type == BeautyViewType_Beauty)
        {
            [weakSelf onBeautyChanged:beauty];
        }
    };

    [beautyView setBeautyValue:_lastBeautyValue];
    

}


//3.调用预处理接口
- (void)OnLocalVideoPreProcess:(QAVVideoFrame *)frame
{
    TILDataType type = TILDataType_NV12;
    switch (frame.frameDesc.color_format)
    {
        case AVCOLOR_FORMAT_I420:
            type = TILDataType_I420;
            break;
        case AVCOLOR_FORMAT_NV12:
            type = TILDataType_NV12;
            break;
        default:
            break;
    }
    [self.tilFilter processData:frame.data inType:type outType:type size:frame.dataSize width:frame.frameDesc.width height:frame.frameDesc.height];
}

- (void)onBeautyChanged:(CGFloat)value
{
    _lastBeautyValue = value;
    NSInteger be = (NSInteger)((value + 0.05) * 10);
    [self setTilBeauty:be];
    [self setTilWhite:be];

}

- (void)setTilBeauty:(float)beauty
{
    [self.tilFilter setBeautyLevel:beauty];
}

- (void)setTilWhite:(float)white
{
    [self.tilFilter setWhitenessLevel:white];
}
#pragma mark ================渐变===============是否有震荡==============
- (void)drawRect:(CGRect)rect {
    
    /**
     *  1.通过CAGradientLayer 设置渐变的背景。
     */
    CAGradientLayer *layer = [CAGradientLayer new];
    //colors存放渐变的颜色的数组
    //    163 216 250
    layer.colors=@[(__bridge id)RGB(163, 216, 250).CGColor,(__bridge id)[UIColor whiteColor].CGColor];
    /**
     * 起点和终点表示的坐标系位置，(0,0)表示左上角，(1,1)表示右下角
     */
    layer.startPoint = CGPointMake(0.3, 0);
    layer.endPoint = CGPointMake(0.3, 0.6);
    layer.frame = _gradually.bounds;
    [_gradually.layer addSublayer:layer];
    
    /**
     *  方法2.CGGradientRef
     */
    
    CGContextRef ctx = UIGraphicsGetCurrentContext();
    CGColorSpaceRef colorSpace=CGColorSpaceCreateDeviceRGB();
    /*指定渐变色
     space:颜色空间
     components:颜色数组,注意由于指定了RGB颜色空间，那么四个数组元素表示一个颜色（red、green、blue、alpha），
     如果有三个颜色则这个数组有4*3个元素
     locations:颜色所在位置（范围0~1），这个数组的个数不小于components中存放颜色的个数
     count:渐变个数，等于locations的个数
     */
    CGFloat compoents[12]={
        0,0,0,1,
        0.8,0.1,0.5,1.0,
        1.0,1.0,1.0,1.0
    };
    
    //设置渐变的位置
    CGFloat locations[3]={0,0.3,1.0};
    //创建梯度上下文
    CGGradientRef gradient= CGGradientCreateWithColorComponents(colorSpace, compoents, locations, 3);
    
    /*绘制线性渐变
     context:图形上下文
     gradient:渐变色
     startPoint:起始位置
     endPoint:终止位置
     options:绘制方式,kCGGradientDrawsBeforeStartLocation 开始位置之前就进行绘制，到结束位置之后不再绘制，
     kCGGradientDrawsAfterEndLocation开始位置之前不进行绘制，到结束点之后继续填充
     
     startPoint endPoint 不同与上一种方法，指的是真正的坐标
     */
    CGContextDrawLinearGradient(ctx, gradient, CGPointMake(_gradually.frame.size.width/2, 0), CGPointMake(_gradually.frame.size.width/2,_gradually.frame.size.height), kCGGradientDrawsAfterEndLocation);
    
    //释放颜色空间
    CGColorSpaceRelease(colorSpace);
}
- (void)animateWave{
    
    
    [UIView animateWithDuration:1 animations:^{
        
        _firstWare.transform = CGAffineTransformMakeTranslation(0, 20);
        
        _secondWare.transform = CGAffineTransformMakeTranslation(0, 20);
        
        _theerWare.transform =CGAffineTransformMakeTranslation(0, 20);
    } completion:^(BOOL finished) {
        
        [UIView animateWithDuration:1 animations:^{
            
            _firstWare.transform = CGAffineTransformMakeTranslation(0, 0);
            
            _secondWare.transform = CGAffineTransformMakeTranslation(0, 0);
            
            _theerWare.transform =CGAffineTransformMakeTranslation(0, 0);
            
        } completion:nil];
        
    }];
    
}

/*!
 @abstract      远程画面回调
 @param         frameData       远端视频帧数据
 @see           QAVVideoFrame
 */
- (void)OnVideoPreview:(QAVVideoFrame *)frameData{
    //仅仅是为了打log
    NSString *key = frameData.identifier;
    QAVFrameDesc *desc = [[QAVFrameDesc alloc] init];
    desc.width = frameData.frameDesc.width;
    desc.height = frameData.frameDesc.height;
    [_parView.resolutionDic setObject:desc forKey:key];
}
/*!
 @abstract      本地画面预览回调
 @param         frameData       本地视频帧数据
 @see           QAVVideoFrame
 */
- (void)OnLocalVideoPreview:(QAVVideoFrame *)frameData{
    //仅仅是为了打log
    NSString *key = frameData.identifier;
    if (key.length == 0)
    {
        key = [[ILiveLoginManager getInstance] getLoginId];
    }
    QAVFrameDesc *desc = [[QAVFrameDesc alloc] init];
    desc.width = frameData.frameDesc.width;
    desc.height = frameData.frameDesc.height;
    [_parView.resolutionDic setObject:desc forKey:key];
}


/*!
 @abstract      摄像头返回的本地画面原始数据
 @param         buf             本地视频帧原始数据
 @param         ret             本地视频帧原始数据
 */
- (void)OnLocalVideoRawSampleBuf:(CMSampleBufferRef)buf result:(CMSampleBufferRef *)ret{
}
- (BOOL)prefersStatusBarHidden{
    return YES;
}
- (BOOL)onRoomDisconnect:(int)reason{
    return YES;
}
#pragma mark ================充值================
- (void)getUserInfoRequestDate{
    [HcardHttpmanager getPersionalInfosuccess:^(id sucess) {
        
        if ([sucess[@"code"] isEqualToString:@"ok" ]) {
            _infomodel   = [UserpersionlInfoModel mj_objectWithKeyValues:sucess[@"res"]];
            
        }
        
    } failure:^(NSError *error) {
        
    }];
}
-(void)moneyButtonClick:(UIButton *)sender{
    
WEAKSELF
    

    [[SKPaymentQueue defaultQueue] addTransactionObserver:self];

    
    [weakSelf getUserInfoRequestDate];
    

    
    if (_infomodel != nil) {
        if (sender.tag == 0) {
            _productID = ProductID_IAP0p6;
            _moneyStr = @"6.00";
            _payMoneyStr = @"42";
  
        }else if (sender.tag == 1){
            _productID = ProductID_IAP1p30;
            _moneyStr = @"30.00";
            _payMoneyStr = @"210";
            
        }else if (sender.tag == 2){
            _productID = ProductID_IAP2p98;
            _moneyStr = @"98.00";
            _payMoneyStr = @"686" ;
            
        }else{
            _productID = ProductID_IAP3p298;
            _moneyStr = @"298.00";
            _payMoneyStr = @"2086" ;
            
        }
        
        
        if ([SKPaymentQueue canMakePayments]) {
            NSLog(@"允许");
            [weakSelf requestProductData:_productID];
        }else{
            NSLog(@"不允许");
        }
        [SVProgressHUD show];

    }
    
    
}

-(void)requestProductData:(NSString *)ProductId{
    NSLog(@"请求对应的产品信息");
    NSSet *nsset = [NSSet setWithObjects:ProductId, nil];
    _requestSk = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    _requestSk.delegate = self;
    [_requestSk start];
}

//收到产品信息

-(void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    
    NSLog(@"收到产品返回信息");
    
    NSArray *productArr = response.products;
    if (productArr.count == 0) {
        NSLog(@"没有数据");
        
        return;
    }
    
    NSLog(@"productID：%@",response.invalidProductIdentifiers);
    NSLog(@"产品付费数量:%lu",(unsigned long)[productArr count]);
    
    SKProduct *prod = nil;
    
    for (SKProduct *pro in productArr) {
        NSLog(@"%@",pro.description);
        NSLog(@"%@",pro.localizedDescription);
        NSLog(@"%@",pro.localizedTitle);
        NSLog(@"%@",pro.price);
        NSLog(@"%@",pro.productIdentifier);
        
        if ([pro.productIdentifier isEqualToString:_productID]) {
            prod = pro;
        }
    }
    
    if (prod != nil) {
        SKPayment  *payment = [SKPayment paymentWithProduct:prod];
        
        NSLog(@"发送购买请求");
        [[SKPaymentQueue defaultQueue] addPayment:payment];
        
    }
    
    
}

//失败请求

- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    [SVProgressHUD dismiss];
    NSLog(@"-----------错误-------------");
    [SVProgressHUD showSuccessWithStatus:@"购买失败"];
}

-(void)requestDidFinish:(SKRequest *)request{
    NSLog(@"请求信息结束");
}



-(void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray<SKPaymentTransaction *> *)transactions{
    for (SKPaymentTransaction *tran in transactions) {
        NSLog(@"打印错误日志----%@",tran.error.description);
        
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:{
                NSLog(@"交易完成");
                [SVProgressHUD dismiss];

                [self completeTransaction:tran];
                [[SKPaymentQueue defaultQueue] finishTransaction:tran];
            }
                break;
            case SKPaymentTransactionStateFailed:{//交易失败
                [self failedTransaction:tran];
            }
                break;
            case SKPaymentTransactionStateRestored:{//已经购买过该商品
                [self restoreTransaction:tran];
            }
                break;
            case SKPaymentTransactionStatePurchasing:      //商品添加进列表
                NSLog(@"商品添加进列表");
                break;

            default:
                break;
        }
        
        
    }
    [SVProgressHUD dismiss];
}

- (void)restoreTransaction:(SKPaymentTransaction *)transaction {
    // 对于已购商品，处理恢复购买的逻辑
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}
- (void)failedTransaction:(SKPaymentTransaction *)transaction {
    if(transaction.error.code != SKErrorPaymentCancelled) {
        NSLog(@"购买失败");
    } else {
        NSLog(@"用户取消交易");
    }
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}

- (void)completeTransaction:(SKPaymentTransaction *)transaction{
    
    if (transaction.transactionState == SKPaymentTransactionStatePurchased) {
        
        
        [HcardHttpmanager inOutCharmWithCharm:_payMoneyStr withCost:_moneyStr withNote:@"苹果内购" withType:KInCharmType withTransNo:@"" withCharm1:@"" withfirstCharge:_infomodel.firstCharge  success:^(id result) {
            if(result){
                [SVProgressHUD dismiss];

            }
        } failure:^(NSError *error) {
            
        }];
        NSLog(@"交易结束");
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.8 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [SVProgressHUD dismiss];
    });
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
    
}
- (void)viewDidUnload {
    [super viewDidUnload];
    [[SKPaymentQueue defaultQueue] removeTransactionObserver:self];

}
@end



